package com.demo.resourcecode.c11mvc.servletasync;

import java.io.IOException;

import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/sasync")
public class ServletAsyncController {

	private static final Logger logger = LoggerFactory.getLogger(ServletAsyncController.class);

	@ResponseBody
    @GetMapping("/hello")
    public void helloGet(HttpServletRequest request) throws Exception {
		try{
	        AsyncContext context = request.startAsync();
	        logger.info("main");
	        context.start(new Runnable(){
	            @Override
	            public void run() {
	            	try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
	            	logger.info("sub");
	                try {
						context.getResponse().getWriter().write("aaa");
					} catch (IOException e) {
						e.printStackTrace();
					}
	                context.complete();
	            }});

	        // 默认将异步任务委托到tomcat io线程池中运行
            // 在tomcat原生异步实现的API中，任务是占用了tomcat io线程的。我们并不建议这样做，因为io线程是servlet的运行线程，所以当大量异步任务开启的时候势必会占用io线程池中的大量资源。从而影响servlet请求的运行，进而影响了服务器的吞吐率
    		// 所以在这种情况下我们建议引入业务线程池，将异步任务在业务线程池中运行，得到结果，设置响应，结束异步。这样释放io线程，避免影响服务器吞吐率，见《spring_resource_demo》的com.demo.resourcecode.c11mvc.servletasync.ServletAsyncController
	        /** 声明自己的业务线程池
	         * ThreadPool pool = ThreadPool.getThreadPool();
	        pool.execute(new Runnable(){
	            @Override
	            public void run() {
	            	...
	                //Complate asyn thread
	                context.complete();
	            }});*/

	    }catch(Exception ex){
	        //Handle exception here
	    }
    }

}
